package config

import (
	"github.com/sirupsen/logrus"
	"todo-list/utils/yaml"
)

const (
	Tag        = "Tag"
	Field      = "Field"
	Msg        = "Message"
	TaskStatus = "TaskStatus"
)

var TranslateDict *Dict

func loadLocals(lang string) error {
	path := getFullPath(Configs.I18n.GetString(lang))
	dict := make(Dict)
	err := yaml.ReadYaml(path, &dict)
	if err != nil {
		logrus.Errorln(err.Error())
		return err
	}
	TranslateDict = &dict
	return nil
}

func TranslateMsg(msg string) string {
	return Translate(Msg, msg)
}
func TranslateTag(msg string) string {
	return Translate(Tag, msg)
}
func TranslateField(msg string) string {
	return Translate(Field, msg)
}
func TranslateTaskStatus(msg string) string {
	return Translate(TaskStatus, msg)
}

func Translate(keys ...string) string {
	dict := *TranslateDict
	for index, k := range keys {
		if index == len(keys)-1 {
			return getTranslation(dict, k)
		}
		ok := getSubDict(&dict, k)
		if !ok {
			return ""
		}
	}
	return ""
}

func getTranslation(dict Dict, key string) string {
	for k, v := range dict {
		if k == key {
			if value, ok := v.(string); ok {
				return value
			}
		}
	}
	return key
}

func getSubDict(dict *Dict, key string) bool {
	for k, v := range *dict {
		if k != key {
			continue
		}
		*dict = v.(Dict)
		return true
	}
	dict = &Dict{}
	return false
}
